package com.baiyang.server.service.impl;

import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSONObject;
import com.baiyang.server.dao.BaseDao;
import com.baiyang.server.model.PageEntity;
import com.baiyang.server.service.BaseService;
import com.baiyang.server.tools.Letter;

@Transactional
public class BaseServiceImpl<M extends BaseDao<T>,T> implements BaseService<T>{
	@Autowired
	private M dao;
	@Override
	public T selectOne(T t) {
		return dao.selectOne(t);
	}
	@Transactional
	@Override
	public boolean insert(T t) {
		try {
			dao.insert(t);
		} catch (Exception e) {
			e.printStackTrace();
			// 插入失败 手动回退
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			throw e;
		}
		return true;
	}
	@Override
	public boolean delete(T t) {
		if(dao.selectOne(t) != null) {
			dao.delete(t);
			return true;
		}else {
			return false;
		}
	}
	@Override
	public void updateById(T t) {
		dao.updateById(t);
	}
	@Override
	public String insertBatch(List<T> ts, Letter<String> letter) {

		return null;
	}
	@Override
	public void insertBatch(List<T> ts) {
		dao.insertBatch(ts);
	}
	@Override
	public int getCount(T t) {
		return 0;
	}
	@Override
	public void deletes(List<T> ts) {
		dao.deletes(ts);
	}
	@Transactional(readOnly = true)
	@Override
	public PageEntity<T> getPage(JSONObject object) {
		PageEntity<T> pageEntity = null;
		try {
			pageEntity = new PageEntity<T>(object);
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
			pageEntity = new PageEntity<T>();
			pageEntity.setResult("ERROR");
			return pageEntity;
		}
		pageEntity.setDatas(dao.getPage(pageEntity));
		pageEntity.setCount(dao.getCount(pageEntity.getO()));
		return pageEntity;
	}
	@Override
	public List<T> selectList(T t) {
		return dao.selectList(t);
	}
}
